<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<?php 
	if( !isset($_COOKIE["username"]) ){
		echo "<script>window.location.href='login.php'</script>";
	}else{
		setcookie("username", $_COOKIE["username"],time() + 900);
	}
?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Patient Info </title>
<link href="css/template.css" rel="stylesheet" type="text/css" />
<link href="css/TestPatient.css" rel="stylesheet" type="text/css"/>
<script src="js/droplinemenu.js" type="text/javascript"></script>
<script src="js/OperateTool.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
//build menu with DIV ID="myslidemenu" on page:
droplinemenu.buildmenu("nav")
</script>

<link href="css/ui-lightness/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery-ui-1.9.2.custom.js"></script>

<!-- datetime select -->
<link rel="stylesheet" href="css/main.css">
<script type="text/javascript" language="javascript" src="js/prototype-1.js"></script>
<script type="text/javascript" language="javascript" src="js/prototype-base-extensions.js"></script>
<script type="text/javascript" language="javascript" src="js/prototype-date-extensions.js"></script>
<script type="text/javascript" language="javascript" src="js/behaviour.js"></script>
<script type="text/javascript" language="javascript" src="js/datepicker.js"></script>
<link rel="stylesheet" href="css/datepicker.css">
<script type="text/javascript" language="javascript" src="js/behaviors.js"></script>
<script type="text/javascript" language="javascript" src="js/upfile.js"></script>

<script language="javascript" >
	function nextDiv(divID){
		var basicInfo = document.getElementById("basicInfo");
		basicInfo.style.display="none";
		var advancedInfo = document.getElementById("advanceInfo");
		advancedInfo.style.display="none";
		

		var current = document.getElementById(divID);
		current.style.display="block";
	}

	jQuery(document).ready(function(){
		jQuery("#AddDoctorDialog").dialog({
			autoOpen:false,
			width:1000,
			modal:true,
			buttons:[
					{
						text: "Add",
						id:"operateButton",
						click:function(){
							

							document.getElementById("doctorFirstNameError").innerHTML = "";
							document.getElementById("doctorSurnameError").innerHTML = "";
							document.getElementById("telephoneError").innerHTML = "";
							
							var doctorNo = 0;
							
							var doctorFirstName = document.getElementById("doctorFirstName").value;
							if( doctorFirstName == "" ){
								document.getElementById("doctorFirstNameError").innerHTML = "please input!!!";
								document.getElementById("doctorFirstName").focus();
								return;
							}
							
							var doctorSurname = document.getElementById("doctorSurname").value;
							if( doctorSurname == "" ){
								document.getElementById("doctorSurnameError").innerHTML = "please input!!!";
								document.getElementById("doctorSurname").focus();
								return;
							}
							
							var doctorTitle = document.getElementById("doctorTitle").value;
							var doctorKnownAs = document.getElementById("doctorKnownAs").value;
							var doctorAddress = document.getElementById("doctorAddress").value;
							
							var doctorTelephone = document.getElementById("doctorTelephone").value;
							if( doctorTelephone != "" ){
								var reg = new RegExp("^[0-9]+$");
								if( reg.test(doctorTelephone) == false ){
									document.getElementById("telephoneError").innerHTML = "format error!!!";
									document.getElementById("doctorTelephone").focus();
									return;
								}
							}
							
							
							var isInCirculateList = 0;
							if( document.getElementById("isInCirculateList").checked == true ){
								isInCirculateList = 1;
							}
							var portrait = document.getElementById("doctorPortraitHidden").value;
							var clinicNo = document.getElementById("clinicNo").value;
							
							var postData = "doctorNo=" + doctorNo + "&doctorFirstName=" + doctorFirstName + "&doctorSurname=" + doctorSurname + "&doctorTitle=" + 
							doctorTitle + "&doctorKnownAs=" + doctorKnownAs + " &doctorAddress=" + doctorAddress + "&doctorTelephone=" + doctorTelephone + "&isInCirculateList=" + isInCirculateList + "&portraitHidden=" + portrait + "&clinicNo=" + clinicNo;									
							
							
							
							jQuery.ajax({type:'post', async:false,dataType:'json', url:'add_doctor.php', data:postData, success:function(result){

									if( result.data.status == "success" ){
										alert("Add doctor success");
										jQuery("#AddDoctorDialog").dialog("close");
										var doctorListObject = document.getElementById("doctor");
										var optionItem = new Option(result.data.doctorFirstName + "  " + result.data.doctorSurname, result.data.doctorNo);
										doctorListObject.options.add(optionItem);
										
									}else{
										alert("Add doctor fail!!!" + result.data.msg);
									}
								},
								error:function (XMLHttpRequest, textStatus, errorThrown){
									alert(XMLHttpRequest.responseText);
								}
							});
							
						}
					},
					{
						text:"Cancel",
						click:function(){
							jQuery(this).dialog("close");
						}
					}
				]		
		});


		jQuery("#leaveDialog").dialog({
			autoOpen:false,
			modal:true,
			width:400,
			buttons:[
			         {
				         text:"Yes",
				         click:function(){
					         
				        	if( patientSubmit() == false ){
				        		jQuery(this).dialog("close");
					        	return;
				        	}
				        	isChange = false;
				        	previousPage();
				         }
				         
			         },
			         {
				         text:"No",
				         click:function(){
				        	isChange = false;
				        	previousPage();
				         }
			         },
			         {
				         text:"Cancel",
				         click:function(){
					         jQuery(this).dialog("close");
				         }
			         }
					]
			
		});

		jQuery("#leaveDialog").dialog({
			autoOpen:false,
			modal:true,
			width:400,
			buttons:[
			         {
				         text:"Yes",
				         click:function(){
					         
				        	if( patientSubmit() == false ){
				        		jQuery(this).dialog("close");
					        	return;
				        	}
				        	isChange = false;
				        	previousPage();
				         }
				         
			         },
			         {
				         text:"No",
				         click:function(){
				        	isChange = false;
				        	previousPage();
				         }
			         },
			         {
				         text:"Cancel",
				         click:function(){
					         jQuery(this).dialog("close");
				         }
			         }
					]
			
		});
		jQuery("#selectDoctorDialog").dialog({
			autoOpen:false,
			modal:true,
			width:1400
		});
		
		var datepicker_CurrentInput;  
        jQuery.datepicker.setDefaults({ showButtonPanel: true, closeText: 'clear', beforeShow: function (input, inst) { datepicker_CurrentInput = input; } });  
        jQuery(".ui-datepicker-close").live("click", function (){  
            datepicker_CurrentInput.value = "";  
        });  
		
		jQuery("#dateBirth1").datepicker({
			dateFormat:'dd/mm/yy',
			changeMonth:true,
			changeYear:true,
			yearRange:'1910:2043'
		});

		jQuery("#dateLastAK").datepicker({
			dateFormat:'dd/mm/yy',
			changeMonth:true,
			changeYear:true,
			yearRange:'1910:2043'
		});
		jQuery("#dateLastSL").datepicker({
			dateFormat:'dd/mm/yy',
			changeMonth:true,
			changeYear:true,
			yearRange:'1910:2043'
		});
		jQuery("#dateLastWait").datepicker({
			dateFormat:'dd/mm/yy',
			changeMonth:true,
			changeYear:true,
			yearRange:'1910:2043'
		});

		if( document.getElementById("deleteButton").getAttribute("disabled") == "disabled" ){
			document.getElementById("deleteButton").disabled = "disabled";
		}
	});


	function popSelectDoctor(){
		jQuery("#selectDoctorDialog").dialog("open");
	}
	
	function popAddDoctor(){
		clearDoctorDialog();
		jQuery("#AddDoctorDialog").dialog("open");
	}


	function selectDoctor(doctorNo, doctorName){
		document.getElementById("doctorName").innerHTML = doctorName;
		document.getElementById("doctorNo").value = doctorNo;
		document.getElementById("selectDoctorLabel").innerHTML = "";
		jQuery("#selectDoctorDialog").dialog("close");
		
	}


	function filterDoctor(){
		var doctorNo = document.getElementById("doctorNoInQuery").value;
		var doctorFirstName = document.getElementById("firstNameInQuery").value;
		var doctorSurname = document.getElementById("surnameInQuery").value;
		var clinicNo = document.getElementById("clinicInQuery").value;


		var flag = false;
		
		if( doctorNo == "" ){
			doctorNo = 0;
		}else{
			flag = true;
		}

		if( doctorFirstName == "" ){
			doctorFirstName = 0;
		}else{
			flag = true;
		}

		if( doctorSurname == "" ){
			doctorSurname = 0;
			
		}else{
			flag = true;
		}

		if( clinicNo != 0 ){
			flag = true;
		}

		//if( flag == false ){
		//	alert("please input query parameter!!!");
		//	return;
		//}

		var postData = "doctorNo=" + doctorNo + "&firstName=" + doctorFirstName + "&surname=" + doctorSurname + "&clinicNo=" + clinicNo;
		jQuery.ajax({type:'post', async:false,dataType:'json', url:'get_doctor_info.php', data:postData, success:function(result){

			var tableObject = document.getElementById("doctorTable");
			var childs = tableObject.childNodes;
			for( var i =childs.length - 1; i >= 0; i-- ){
				tableObject.removeChild(childs[i]);
			}

			for( var i = 0; i < result.data.length; i++ ){

				
				var doctorNoTd = document.createElement("td");
				doctorNoTd.innerHTML = result.data[i].doctorNo;
				doctorNoTd.setAttribute("width", "10%");

				var firstNameTd = document.createElement("td");
				firstNameTd.innerHTML = result.data[i].firstName.replace("'", "\'");
				firstNameTd.setAttribute("width", "18%");
				//alert("123");
				var surnameTd = document.createElement("td");
				surnameTd.innerHTML = result.data[i].surname.replace("'", "\'");
				surnameTd.setAttribute("width", "18%");

				var addressTd = document.createElement("td");
				addressTd.innerHTML = result.data[i].address.replace("'", "\'");
				addressTd.setAttribute("width", "26%");

				
				var clinicTd = document.createElement("td");
				clinicTd.innerHTML = result.data[i].clinicName.replace("'", "\'");
				clinicTd.setAttribute("width", "18%");

				var operateTd = document.createElement("td");
				var selectLink = document.createElement("a");
				selectLink.href = "#";
				//var firstName = result.data[i].firstName.replace
				
				//alert("456");
				selectLink.innerHTML = "select";
				//alert(result.data[i].surname.replace("'", "\'"));
				//alert("selectDoctor('" + result.data[i].doctorNo + "','" + result.data[i].firstName.replace("'", "\'") + " " + result.data[i].surname.replace("'", "\'") + "')");
				selectLink.onclick = new Function("selectDoctor('" + result.data[i].doctorNo + "','" + result.data[i].firstName.replace("'", "\'") + " " + result.data[i].surname.replace("'", "\\'") + "')");
				//alert('3214');
				operateTd.appendChild(selectLink);
				operateTd.setAttribute("width", "10%");
				//alert("3456889");
				var childTrElement = document.createElement("tr");
				
				childTrElement.appendChild(doctorNoTd);
				//alert("456123");
				childTrElement.appendChild(firstNameTd);
				
				childTrElement.appendChild(surnameTd);
				childTrElement.appendChild(addressTd);
				
				childTrElement.appendChild(clinicTd);
				childTrElement.appendChild(operateTd);

				tableObject.appendChild(childTrElement);
				
				//alert("789");
			}

		},
		error:function (XMLHttpRequest, textStatus, errorThrown){
			document.getElementById("errorMsg").innerHTML =XMLHttpRequest.responseText; 
			//alert(XMLHttpRequest.responseText);
			alert(textStatus);
			alert(errorThrown);
		}
	});
		
	}



	function clearDoctorDialog(){
		document.getElementById("doctorFirstName").value = "";
		document.getElementById("doctorSurname").value = "";
		document.getElementById("doctorTitle").value = "";
		document.getElementById("doctorKnownAs").value = "";
		document.getElementById("doctorAddress").value = "";
		document.getElementById("doctorTelephone").value = "";
		document.getElementById("isInCirculateList").checked = false;
		document.getElementById("doctorPortraitHidden").value = "";
		document.getElementById("doctorPortraitImg").src = "";
		document.getElementById("selectDoctorLabel").innerHTML = "";
		
	}

	function uploadCallback(filename){
		if( filename == "" ){
			document.getElementById("portraitImg").setAttribute("src", "./picture");
		}else{
			document.getElementById("portraitImg").src = filename;
		} 
		document.getElementById("portrait").outerHTML = document.getElementById("portrait").outerHTML;
		document.getElementById("portraitHidden").value = filename;
		document.getElementById("patientPortraitError").innerHTML = "";
		changeFunc();
	}


	function uploadDoctorCallback(filename){
		if( filename == "" ){
			document.getElementById("doctorPortraitImg").src = "./piture";
		}else{
			document.getElementById("doctorPortraitImg").src = filename;
		}
		document.getElementById("doctorPortrait").outerHTML = document.getElementById("portrait").outerHTML;
		document.getElementById("doctorPortraitHidden").value = filename;
		document.getElementById("doctorPortraitError").innerHTML = "";
	}


	function patientSubmit(){
		//clear the error message
		clearErrorMessage();



		
		var patientNoObject = document.getElementById("patientNo");
		var patientNo = patientNoObject.value;
		var patientReg = new RegExp("^[0-9]+$");
		//alert(checkPatientNo(patientNo) + "check");
		if( patientNo == "" ){
			nextDiv("basicInfo");
			patientNoObject.focus();
			document.getElementById("patientNoError").innerHTML = "Should not empty !!!";
			return;
		}
		if( document.getElementById("submitButton").value == "Add" ){
			if( checkPatientNo(patientNo) == false ){
				return;
			}
		}


		var patientFirstNameObject = document.getElementById("patientFirstName");
		var patientFirstName = patientFirstNameObject.value;
		if( patientFirstName == "" ){
			patientFirstNameObject.focus();
			nextDiv("basicInfo");
			document.getElementById("patientFirstNameError").innerHTML = "please input!!!!";
			return false;	
		}

		var patientSurnameObject = document.getElementById("patientSurname");
		var patientSurname = patientSurnameObject.value;
		if( patientSurname == "" ){
			patientSurnameObject.focus();
			nextDiv("basicInfo");
			document.getElementById("patientSurnameError").innerHTML = "please input!!!";
			return false;
		}

		var mobileObject = document.getElementById("mobile");
		var mobile = mobileObject.value;

		if( mobile != "" ){
			var reg = new RegExp("^[0-9]+$");
			if( reg.test(mobile) == false ){
				mobileObject.focus();
				nextDiv("basicInfo");
				document.getElementById("mobileError").innerHTML = "format error!!!!";
				return false;
			}
		}


		var landlineObject = document.getElementById("landline");
		var landline = landlineObject.value;

		if( landline != "" ){
			var reg = new RegExp("^[0-9]+$");
			if( reg.test(landline) == false ){
				landlineObject.focus();
				nextDiv("basicInfo");
				document.getElementById("landlineError").innerHTML = "format  error!!!!";
				return false;
			}
		}

		//var reg = new RegExp("^(((((0[13578]|1[02]))-(0[1-9]|[12][0-9]|3[01])|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02)-(0[1-9]|[1][0-9]|2[0-8]))-([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3}))|(02-29-(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))))$");
		
		var dateBirthObject = document.getElementById("dateBirth1");
		var dateBirth = dateBirthObject.value;
		//if( dateBirth != "" ){
		//	if( reg.test(dateBirth) == false ){
		//		dateBirthObject.focus();
		//		document.getElementById("dateBirthError").innerHTML = "the format of the date birth is error!!!";
		//		return false;
		//	}
		//}

		var dateLastAKObject = document.getElementById("dateLastAK");
		var dateLastAK = dateLastAKObject.value;
		//if( dateLastAK != "" ){
		//	if( reg.test(dateLastAK) == false ){
		//		dateLastAKObject.focus();
		//		document.getElementById("dateLastAKError").innerHTML = "the format of the dateLastAK is error!!!";
		//		return false;
		//	}
		//}


		var dateLastSLObject = document.getElementById("dateLastSL");
		var dateLastSL = dateLastSLObject.value;
		//if( dateLastSL != "" ){
		//	if( reg.test(dateLastSL) == false ){
		//		dateLastSLObject.focus();
		//		document.getElementById("dateLastSLError").innerHTML = "the format of the dateLastSL is error!!!";
		//		return false;
		//	}
		//}
		
		var dateLastWaitObject = document.getElementById("dateLastWait");
		var dateLastWait = dateLastWaitObject.value;
		//if( dateLastWait != "" ){
		//	if( reg.test(dateLastWait) == false ){
		//		dateLastWaitObject.focus();
		//		document.getElementById("dateLastWaitError").innerHTML = "the format of the dateLastWait is error!!!";
		//		return false;
		//	}
		//}

		var patientNo = document.getElementById("patientNo").value;
		var address = jQuery("#address").val();
		var sex = document.getElementById("sex").value;
		var portraitHidden = document.getElementById("portraitHidden").value;
		var dateBirth = document.getElementById("dateBirth1").value;
		var pastHistory = jQuery("#pastHistory").val();
		var drugsAllergies = jQuery("#drugsAllergies").val();
		var insurer = document.getElementById("insurer").value;
		var insurerNo = document.getElementById("insurerNo").value;
		var holderName = document.getElementById("holderName").value;
		var doctorObject = document.getElementById("doctorNo");
		var doctorNo = doctorObject.value;

		if( doctorNo == 0 ){
			document.getElementById("selectDoctorLabel").innerHTML = "select doctor";
			document.getElemetnById("selectDoctorButton").focus();
			return;
		}
		
		//if( doctorNo == undefined || doctorNo == "" ){
			//alert("1");
			//nextDiv("advanceInfo");
			//doctorObject.focus();
			//document.getElementById("doctorError").innerHTML = "select a doctor!!";
			//return false;
			
		//}

		if( isChange == false ){
			alert("no change occur");
			return;
		}

		var username = getCookie("username");
		
		var isSuccess = false;
		var postData = "patientNo=" + patientNo + "&patientFirstName=" + patientFirstName + "&patientSurname=" +patientSurname + "&mobile=" + mobile + 
		"&address=" + address + "&landline=" + landline + "&sex=" + sex + "&portratiHidden=" + portraitHidden + "&dateBirth=" + dateBirth + "&pastHistory=" + 
		pastHistory + "&drugsAllergies=" + drugsAllergies + "&insurer=" + insurer + "&insurerNo=" + insurerNo + "&holderName=" + holderName + "&dateLastAK=" 
		+ dateLastAK + "&dateLastSL=" + dateLastSL + "&dateLastWait=" + dateLastWait + "&portraitHidden=" + portraitHidden + "&doctorNo=" + doctorNo + "&username=" + username;
		jQuery.ajax({type:'post', async:false, dataType:'json', url:'operate_patient_info.php', data:postData, success:function(result){
				if( result.data.status == "success" ){
					alert(result.data.type + " patient " + result.data.patientNo + " success !!!");
					isChange = false;
					if( result.data.type == "Add" ){
						window.location.href = "patient_account.php?patientNo=" + result.data.patientNo;
						return;
					}
					previousPage();
					document.getElementById("submitButton").value = "Update";
					document.getElementById("deleteButton").disabled = false;
					document.getElementById("patientNo").value = result.data.patientNo;
					isSuccess = true;
					
				}else{
					alert(result.data.type + " fail !!!" + result.data.msg);
				}
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				alert(XMLHttpRequest.responseText);
			}
		});
		
		
		return isSuccess;
		
	}


	function deleteObject(){
		var confirmResult = confirm("are you sure delete this patient info??");
		if( confirmResult == false ){
			return ;
		}

		
		var patientNo = document.getElementById("patientNo").value;
		jQuery.ajax({type:'post',async:false,data:"No=" + patientNo + "&type=1", dataType:'json', url:'delete_op.php', success:function(result){
				if( result.data.status == "success" ){
					alert("Delete success!!!!");
					//previousPage();
					window.location.href = "list_patient.php";
					
					document.getElementById("patientFirstName").value = "";
					document.getElementById("patientSurname").value = "";
					document.getElementById("mobile").value = "";
					jQuery("#address").val("");
					document.getElementById("landline").value = "";
					document.getElementById("patientFirstName").selectedIndex = 0;
					document.getElementById("portraitImg").src = "";
					document.getElementById("portraitHidden").value = "";
					jQuery("#dateBirth1").val("");
					jQuery("#pastHistory").val("");
					jQuery("#drugsAllergies").val("");
					document.getElementById("insurer").value = "";
					document.getElementById("insurerNo").value = "";
					document.getElementById("holderName").value = "";
					document.getElementById("dateLastAK").value = "";
					document.getElementById("dateLastSL").value = "";
					document.getElementById("dateLastWait").value = "";
					
					document.getElementById("clinic").selectedIndex = 0;
					document.getElementById("operateMsg").innerHTML = "delete patient success!!!";

					document.getElementById("submitButton").value = "Add";
					//document.getElementById("")
					
				}else{
					document.getElementById("operateMsg").innerHTML = "delete patient fail!!! " + result.data.msg;
				}
			},
			error:function (XMLHttpRequest, textStatus, errorThrown){
				alert(XMLHttpRequest.responseText);
				alert(textStatus);
				alert(errorThrown);
			}
		});
		
	}

	var isChange = false;

	function changeFunc(){
		isChange = true;
		clearErrorMessage();
	}


	function clearErrorMessage(){
		document.getElementById("patientNoError").innerHTML = "";
		document.getElementById("patientFirstNameError").innerHTML = "";
		document.getElementById("doctorError").innerHTML = "";
		document.getElementById("patientSurnameError").innerHTML = "";
		document.getElementById("mobileError").innerHTML = "";
	}

	
	function previousPage(){
		if( isChange == true ){
			jQuery("#leaveDialog").dialog("open");
			return;
		}
		
		var lastURL = document.referrer;

		if( lastURL.lastIndexOf("patient_account.php") != -1 ){
			window.location.href = lastURL;
		}else{
				window.location.href = "list_patient.php";
		}
	}

	function leaveBefore(){
		if( isChange == true ){
			return false;
		}
	}


	function checkPatientNo(value){

		var reg = new RegExp("^[0-9]+$");
		if( reg.test(value) == false ){
			document.getElementById("patientNoError").innerHTML = "format error!!!";
			document.getElementById("patientNo").focus();
			return false;
		}
		var isExist = false;
		jQuery.ajax({type:'post', async:false, data:"patientNo=" + value, dataType:'json', url:'patient_exist.php', success:function(result){
				if( result.data.exist == "true" ){
					
					nextDiv("basicInfo");
					document.getElementById("patientNo").focus();
					document.getElementById("patientNoError").innerHTML = "already exist!!";
					isExist = true;
				}else{
					changeFunc();
				}
			},
			error:function(XMLHttpRequest, textStatus, errorThrown){
				alert(XMLHttpRequest.responseText);
			}
		});
		if( isExist == true ){
			return false;
		}else{
			return true;
		}
	}


	function patientPortraitSubmit(inputId, errorId, formId){
		var inputFile = document.getElementById(inputId);
		var errorObject = document.getElementById(errorId);
		var filePath = inputFile.value;
		var errorFlag = false;
		
		if( filePath == undefined || filePath=="" ){
			uploadCallback("");
			errorFlag = true;
		}else{
			var fileArr = filePath.split("//");
			var fileTArr = fileArr[fileArr.length - 1].toLowerCase().split(".");
			var fileType = fileTArr[fileTArr.length - 1].toLowerCase();
			if( fileType != "jpg" && fileType != "jpeg" && fileType != "bmp" && fileType != "png"){
				inputFile.focus();
				errorObject.innerHTML = "the file type error!!!";
				errorFlag = true;
			} 
		}

		if( errorFlag == false ){
			document.getElementById(formId).submit();
		}
	}


	function doctorPortraitSubmit(inputId, errorId, formId){
		var inputFile = document.getElementById(inputId);
		var errorObject = document.getElementById(errorId);
		var filePath = inputFile.value;
		var errorFlag = false;
		if( filePath == undefined || filePath=="" ){
			uploadDoctorCallback("");
			errorFlag = true;
		}else{
			var fileArr = filePath.split("//");
			var fileTArr = fileArr[fileArr.length - 1].toLowerCase().split(".");
			var fileType = fileTArr[fileTArr.length - 1].toLowerCase();
			if( fileType != "jpg" && fileType != "jpeg" && fileType != "bmp" && fileType != "png"){
				inputFile.focus();
				errorObject.innerHTML = "the file type error!!!";
				errorFlag = true;
			} 
		}

		if( errorFlag == false ){
			document.getElementById(formId).submit();
		}
	}



</script>

</head>

<body onbeforeunload="return leaveBefore();">
	<div id="container">
		<div id="header"></div>
		<?php include_once 'nav.php';?>
		<?php 
			$patientNo = 0;
			$firstName = "";
			$surname = "";
			$sex = "";
			$birthDate = "";
			$mobile = "";
			$landline = "";
			$address = "";
			$portrait = "";
			$insurer = "";
			$insurerNo = "";
			$holderName = "";
			$dateLastAK = "";
			$dateLastSL = "";
			$dateLastWait = "";
			$pastHistory = "";
			$doctorNo = 0;
			$drugsAllergies = "";
			$username = $_COOKIE["username"];
			
	
			$ini_array = parse_ini_file("config/config.ini");
		
			$conn = @mysqli_connect($ini_array["host"], $ini_array["username"], $ini_array["password"], $ini_array["db_name"]) or die("cann't connect the mysql db");
			mysqli_set_charset($conn, "utf8");
			ini_set('default_charset', "UTF-8");
			date_default_timezone_set($ini_array["default_timezone"]);
			$buttonText = "Add";
			
			if( isset($_GET["patient_no"]) && preg_match("/^\d+$/", $_GET["patient_no"]) == true){
				$patientNo = $_GET["patient_no"];
				$sql = "SELECT patient.`First_name`, patient.`Surname`, patient.`sex`, patient.`Date_birth`, patient.`mobile`, 
				patient.`landline`, patient.`address`, patient.`portrait_file`, patient.`insurer`, patient.`insurer_no`, patient.`holder_name`, 
				patient.`date_last_ak`, patient.`date_last_sl`, patient.`date_last_wait`, patient.`past_history`, patient.`drugs_allergies`, 
				patient.`doctor_no`, patient.`included` FROM patient  WHERE Patient_no=".$patientNo;
				$result = mysqli_query($conn, $sql);
				echo mysqli_error($conn);
				if( $row = mysqli_fetch_array($result)){
					$firstName = $row["First_name"];
					$surname = $row["Surname"];
					$sex = $row["sex"];
					if( strcmp($row["Date_birth"],"") != 0){
						$birthDate = date("d/m/Y",strtotime($row["Date_birth"]));
					}
					$mobile = $row["mobile"];
					$landline = $row["landline"];
					$address = $row["address"];
					$portrait = $row["portrait_file"];
					$insurer = $row["insurer"];
					$insurerNo = $row["insurer_no"];
					$holderName = $row["holder_name"];
					if( strcmp($row["date_last_ak"],"") != 0 ){
						$dateLastAK = date("d/m/Y", strtotime($row["date_last_ak"]));
					}
					
					if( strcmp($row["date_last_sl"],"") != 0 ){
						$dateLastSL = date("d/m/Y", strtotime($row["date_last_sl"]));
					}
					
					if( strcmp($row["date_last_wait"],"") != 0 ){
						$dateLastWait = date("d/m/Y", strtotime($row["date_last_wait"]));
					}
					$pastHistory = $row["past_history"];
					$drugsAllergies = $row["drugs_allergies"];
					$doctorNo = $row["doctor_no"];
					$username = $row["included"];
					$buttonText = "Update";
					
				}
				
			}else{
				$sql = "select max(patient_no) max from patient;";
				$result = mysqli_query($conn, $sql);
				$row = mysqli_fetch_array($result);
				$patientNo = $row["max"] + 1;
			}
			
		

		?>
		<div id="main_content" style="margin:50px 0px 0px 0px;">
			<div id="basicInfo" style="margin:10px auto;width:840px;">
				
					<table style="width:820px;">
						<tr>
							<td style="width:15%;text-align:right;height:60px;"><label>Patient No.:</label></td>
							<td style="width:20%;"><input type="text" name="patientNo" id="patientNo" value="<?php echo $patientNo?>" <?php if( strcmp($buttonText,"Update")==0 )echo "readonly=\"readonly\""?> onchange="changeFunc()"/></td>
							<td style="width:25%;"><span id="patientNoError"></span></td>
							<td style="width:14%;text-align:right;"><!-- <label>Included:</label> --></td>
							<td style="width:26%;"><!-- <label><?php echo $username?></label> --></td>
						</tr>
						<tr>
							<td style="text-align:right;height:60px;"><label>First Name:</label></td>
							<td><input type="text" name="patientFirstName" id="patientFirstName" value="<?php echo $firstName?>" onchange="changeFunc()"/></td>
							<td><span id="patientFirstNameError"></span></td>
							<td  style="text-align:right;"><label style="display:none;">Portrait:</label></td>
							<td rowspan="2"><img width="56" name="portraitImg" id="portraitImg" height="54" src="<?php echo $portrait?>" style="display:none;"/><input type="hidden" value="<?php echo $portrait?>" name="portraitHidden" id="portraitHidden" onchange="changeFunc()"/></td>
						</tr>
						<tr>
							<td style="text-align:right;height:60px;"><label>Surname:</label></td>
							<td><input type="text" name="patientSurname" id="patientSurname" value="<?php echo $surname?>" onchange="changeFunc()"/></td>
							<td><span id="patientSurnameError"></span></td>
							<td></td>
						</tr>
						<tr>
							<td style="text-align:right;height:60px;"><label>Sex:</label> </td>
							<td>
								<select name="sex" id="sex" onchange="changeFunc()">
									<option value="Male" <?php if(strcmp($sex, "Male") == 0) echo "selected=\"selected\"";?>>Male</option>
									<option value="Female" <?php if(strcmp($sex, "Female") == 0) echo "selected=\"selected\"";?>>Female</option>
								</select>
							</td>
							<td></td>
							<td  style="text-align:right;"><label>Address:</label></td>
							<td rowspan="3"><textarea name="address" id="address" onchange="changeFunc()" style="height:9em;resize:none;"><?php echo $address?></textarea></td>
						</tr>
						<tr>
							<td style="text-align:right;height:60px;"><label>Date of Bith</label></td>
							<td><input type="text" name="dateBirth1" id="dateBirth1"  value="<?php echo $birthDate?>" onchange="changeFunc()" readonly="readonly"/></td>
							<td><span id="dateBirthError" ></span></td>
							<td></td>

						</tr>
						<tr>
							<td style="text-align:right;height:60px;"><label>Mobile:</label></td>
							<td><input type="text" name="mobile" id="mobile" value="<?php echo $mobile?>" onchange="changeFunc()"/></td>
							<td><span id="mobileError"></span></td>
							<td></td>

						</tr>
						<tr>
							<td  style="text-align:right;height:60px;"><label>Landline:</label></td>
							<td><input type="text" id="landline" name="landline" value="<?php echo $landline?>" onchange="changeFunc()"/></td>
							<td><label id="landlineError"></label></td>
							<td><label>Doctor List:</label></td>
							<td>
								<form enctype="multipart/form-data" action="upload_op.php" method="post"target="hidden_frame" id="patientPortraitForm" style="display:none;">
									<input type="file" name="portrait" id="portrait"/><input type="button" value="upload" onclick="patientPortraitSubmit('portrait','patientPortraitError','patientPortraitForm')"/>
									<input type="hidden" name="funcName" id="funcName" value="uploadCallback" />
									<label id="patientPortraitError"></label>
									<iframe name="hidden_frame" id="hidden_frame" style="display:none"></iframe>
								</form>
								<?php 
									$doctorSql = "select doctor_first_name, doctor_surname from doctor where Doctor_no=".$doctorNo;
									$doctorResult = mysqli_query($conn, $doctorSql);
									if( $row = mysqli_fetch_array($doctorResult)){
								?>
										<label id="doctorName"><?php echo $row["doctor_first_name"]." ".$row["doctor_surname"]?></label>
										<input type="hidden" id="doctorNo" value="<?php echo $doctorNo?>" />
								<?php
									 }else{
								?>
									<label id="doctorName"></label>
									<input type="hidden" id="doctorNo" value="0" />
								<?php 
									}
								?>
								<input type="button" value="select doctor" onclick="popSelectDoctor()" id="selectDoctorButton"/> 
								<label id="selectDoctorLabel"></label>
								
							</td>
						</tr>
						<tr>
							<td></td>
							<td></td>
							<td></td>
							<td></td>
							<td><input type="button" value="Add Doctor" onclick="popAddDoctor()" /></td>
						</tr>
					</table>
				<div id="basicBottomPart">
					<input type="button" value="Advanced Info" onclick='nextDiv("advanceInfo")'/>
				</div>
				
			</div>
			<div id="advanceInfo" style="display:none;margin:10px auto;width:900px;">
				
				<table style="width:880px;">
					<tr>
						<td style="height:60px;text-align:right;"><label>Insurer:</label></td>
						<td><input type="text" name="insurer" id="insurer" value="<?php echo $insurer?>"  onchange="changeFunc()"/></td>
						<td style="text-align:right;"><label>Holder Name:</label></td>
						<td><input type="text" name="holderName" id="holderName" value="<?php echo $holderName?>"  onchange="changeFunc()"/></td>
						<td style="text-align:right;"><label>No.:</label></td>
						<td><input type="text" name="insurerNo" id="insurerNo" value="<?php echo $insurerNo?>"  onchange="changeFunc()"/></td>
					</tr>
					<tr>
						<td style="height:60px;text-align:right;"><label>Date Last AK:</label></td>
						<td><input type="text"  name="dateLastAK" id="dateLastAK" value="<?php echo $dateLastAK?>" readonly="readonly" onchange="changeFunc()"/></td>
						<td style="text-align:right;"><label>Date Last SL:</label></td>
						<td><input type="text"  name="dateLastSL" id="dateLastSL" value="<?php echo $dateLastSL?>" readonly="readonly"  onchange="changeFunc()"/></td>
						<td style="text-align:right;"><label>Date Last Wait:</label></td>
						<td><input type="text" name="dateLastWait" id="dateLastWait" value="<?php echo $dateLastWait?>" readonly="readonly"/></td>
					</tr>
					<tr>
						<td colspan="3" style="height:60px;"><label>Past History</label></td>
						<td></td>
						<td></td>
						<td></td>
					</tr>
					<tr>
						<td colspan="6"><textarea name="pastHistory" id="pastHistory" cols="120" style="resize:none;height:4em" onchange="changeFunc()"><?php echo $pastHistory?></textarea></td>
					</tr>
					<tr>
						<td colspan="3" style="height:60px;"><label>Drugs Allergies</label></td>
						<td></td>
						<td></td>
						<td></td>
					</tr>
					<tr>
						<td colspan="6"><textarea name="drugsAllergies" id="drugsAllergies" cols="120" style="resize:none;height:4em;" onchange="changeFunc()"><?php echo $drugsAllergies?></textarea></td>
					</tr>
					<tr>
						<td style="height:60px;"><input type="button" value="Basic Info" onclick='nextDiv("basicInfo")'/></td>
						<td></td>
						<td></td>
						<td>
							
						</td>
						<td></td>
						<td><label id="doctorError"></label></td>
					</tr>
				</table>
				
				

				
			
				
			</div>
			<div id="operatePart" style="margin:30px auto;">
				<input type="button" value="<?php echo $buttonText?>" onclick="patientSubmit()" id="submitButton"/>
				<input type="button" value="delete" onclick="deleteObject()" id="deleteButton" <?php if( strcmp($buttonText, "Add" )==0){echo "disabled=\"disabled\"";}?>/>
				<input type="button" value="return" onclick="previousPage()" id="cancelButton"/>
			</div>
	 		<div id="msgDiv">
				<label id="operateMsg"></label>
			</div>
		</div>
		<?php
			$getClinicSql = "select Clinic_no, Clinic_name from clinic";
			$clinicResult = mysqli_query($conn, $getClinicSql);
		?>

		<div id="AddDoctorDialog" title="Add Doctor" style="display:none">
			<div id="AddDoctorInfoDiv">
				<table>
					<tr>
						<td style="width:20%;text-align:right;"><label>First Name:</label></td>
						<td style="width:20%;"><input type="text" name="doctorFirstName" id="doctorFirstName" /></td>
						<td style="width:20%;"><label id="doctorFirstNameError"></label></td>
						<td style="width:5%;text-align:right;"><div ><label>Clinic:</label></div><div style="display:none;"><label>Portrait:</label></div></td>
						<td style="width:35%;">
							<select name="clinicNo" id="clinicNo" onchange="changeFunc()">
								<?php 
									while( $clinicRow = mysqli_fetch_array($clinicResult)){
								?>
								<option value="<?php echo $clinicRow["Clinic_no"]?>"><?php echo  $clinicRow["Clinic_name"]?></option>
								<?php }?>
							</select>

<div style="display:none;"><img src="" width="100px" height="100px" id="doctorPortraitImg"/><input type="hidden" name="portraitHidden" id="doctorPortraitHidden"/></div></td>
					</tr>
					<tr>
						<td style="text-align:right;"><label>Surname:</label></td>
						<td><input type="text" name="doctorSurname" id="doctorSurname" /></td>
						<td><label id="doctorSurnameError"></label></td>
						<td></td>
						<td></td>
					</tr>
					<tr>
						<td style="text-align:right;"><label>Title:</label></td>
						<td><input type="text" name="doctorTitle" id="doctorTitle"/></td>
						<td></td>
						<td style="text-align:right;"><label>Address:</label></td>
						<td rowspan="3"><textarea  name="doctorAddress" id="doctorAddress" style="height:6em;resize:none;"></textarea></td>
					</tr>
					<tr>
						<td style="text-align:right;"><label>Known As:</label></td>
						<td><input type="text" name="doctorKnownAs" id="doctorKnownAs" /></td>
						<td></td>
						<td></td>
					</tr>
					<tr>
						<td style="text-align:right;"><label>Telephone:</label></td>
						<td><input type="text" name="doctorTelephone" id="doctorTelephone"/></td>
						<td><label id="telephoneError"></label></td>
						<td></td>

					</tr>
					<tr>
						<td style="text-align:right;"><label>In Circulate List?:</label></td>
						<td><input type="checkbox" name="isInCirCulateList" id="isInCirculateList" /></td>
						<td></td>
						<td></td>
						<td>
							<form enctype="multipart/form-data" action="upload_op.php" method="post" target="hidden_frame" id="doctorPortraitForm" style="display:none;">
								<input type="file" name="portrait" id="doctorPortrait" />
								<input type="hidden" name="funcName" id="funcName" value="uploadDoctorCallback" />
								<input type="button" value="upload" onclick="alert('1');doctorPortraitSubmit('doctorPortrait', 'doctorPortraitError', 'doctorPortraitForm')"/>
								<label id="doctorPortraitError"></label>
							</form>
						</td>
					</tr>
				</table>
			</div>
			<label id="msg"></label>
		</div>
		<?php include_once 'footer.php';?>
		
		<div id="leaveDialog" title="leave dialog" style="display:none">
			<label>the patient data have change, do  you save before leave?</label>
		</div>
		
		
		<div id="selectDoctorDialog" title="select doctor" style="display:none">
			<div id="doctorList" style="text-align:center">
				<div><h2>List of Doctors</h2></div>
				
				<div>
					<label>Doctor No.:</label><input type="text" name="doctorNoInQuery" id="doctorNoInQuery" value="" style="width:100px;"/>
					<label>Doctor First Name:</label><input type="text" name="firstNameInQuery" id="firstNameInQuery" value="" style="width:100px;"/>
					<label>Doctor Surname:</label><input type="text" name="surnameInQuery" id="surnameInQuery" value="" style="width:100px;"/>
					<?php 
						$getClinicSql = "select * from clinic";
						$clinicResult = mysqli_query($conn, $getClinicSql);
					?>
					
					
					<label>Clinic:</label>
					<select name="clinicInQuery" id="clinicInQuery">
						<?php 
							$clinicNo = 0;
							if( isset($_POST["clinic"]) ){
								$clinicNo = $_POST["clinic"];
							}
						?>
						<option value="0" <?php if( $clinicNo == 0 ) echo "selected=\"selected\"";?>></option>
						<?php
							while($row = mysqli_fetch_array($clinicResult) ){
						?>
						<option value="<?php echo $row["Clinic_no"]?>" <?php if( $clinicNo == $row["Clinic_no"]) echo "selected=\"selected\"";?>><?php echo $row["Clinic_name"]?></option>
						<?php 
							}
						?>
					</select>
					<input type="button" value="query" onclick="filterDoctor()"/>
				</div>
				
				
				
				<div style="width:135px;display:inline-block;"><label>Doctor No.</label></div>
				<div style="width:135px;display:inline-block;"><label>First Name</label></div>
				<div style="width:135px;display:inline-block;"><label>Surname</label></div>
				<div style="width:180px;display:inline-block;"><label>Address</label></div>
				<div style="width:135px;display:inline-block;"><label>Clinic</label></div>
				<div style="width:135px;display:inline-block;"><label>Operate</label><br /></div>
				
				
				
				
				<div id="doctorList" style="margin:0px auto;width:840px;height:520px;overflow:auto;">
					<table style="width:820px" id="doctorTable">
						<?php
							$getDoctorSql = "select Doctor_no, doctor_first_name, doctor_surname, doctor_address, Clinic_name from doctor left outer join clinic on doctor.clinic_no = clinic.Clinic_no";
							$doctorResult = mysqli_query($conn, $getDoctorSql);
							while( $row = mysqli_fetch_array($doctorResult)){
								$doctorNo = $row["Doctor_no"];
								$doctorFirstName = str_replace("'", "\'", $row["doctor_first_name"]);
								if( strlen($doctorFirstName) > 15 ){
									$doctorFirstName = substr($doctorFirstName, 0, 15);
								}
								
								$doctorSurname = str_replace("'", "\'", $row["doctor_surname"]);
								if( strlen($doctorSurname) > 15 ){
									$doctorSurname = substr($doctorSurname, 0, 15);
								}
								
								$doctorAddress = $row["doctor_address"];
								if( strlen($doctorAddress) > 25 ){
									$doctorAddress = substr($doctorAddress, 0, 36);
								}
								
								$clinicName = $row["Clinic_name"];
								if( strlen($clinicName) > 15 ){
									$clinicName = substr($clinicName, 0, 15);
								} 
								
						?>
						<tr>
							<td style="width:10%;"><?php echo $doctorNo?></td>
							<td style="width:18%;"><?php echo $doctorFirstName?></td>
							<td style="width:18%;"><?php echo $doctorSurname?></td>
							<td style="width:26%;"><?php echo $doctorAddress?></td>
							<td style="width:18%;"><?php echo $clinicName?></td>
							<td style="width:10%;"><a href="#" onclick="selectDoctor(<?php echo "'".$doctorNo."','".$doctorFirstName." ".$doctorSurname."'" ?>)" >select</a></td>
						</tr>
						<?php }?>
					</table>
				</div>
				<label id="errorMsg"></label>
			</div>
		</div>
	</div>
</body>
</html>
